package com.link.gateway.core.filter.visitstatistics.util;

import com.link.gateway.core.redis.redisclient.LinkRedisClient;

import java.util.Collections;

/**
 * 锁定、解锁 redis key
 * @author Li Yang
 */
public class RedisTool {
    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";
    private static final Long RELEASE_SUCCESS = 1L;

    /**
     * 尝试获取分布式锁
     * @param jedis Redis客户端
     * @param lockKey 锁
     * @param requestId 请求标识
     * @param expireTime 超期时间
     * @return 是否获取成功
     */
    public static boolean tryGetDistributedLock(LinkRedisClient jedis, String lockKey, String requestId, int expireTime) {
        String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
        if (LOCK_SUCCESS.equals(result)) {
            return true;
        }
        return false;

    }

    /**
     * 释放分布式锁
     * 目前腾讯云默认不开启redis脚本，只能使用简单的删除key操作
     * 这里有个问题，一但请求时间大于锁的过期时间，则前面请求记录可能会覆盖后面记录
     * @param jedis Redis客户端
     * @param lockKey 锁
     * @param requestId 请求标识
     * @return 是否释放成功
     */
    public static boolean releaseDistributedLock(LinkRedisClient jedis, String lockKey, String requestId) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }
        return false;
//        boolean flag = false;
//        String jedisValue = jedis.get(lockKey);
//        if (requestId.equals(jedisValue) || null == jedisValue) {
//            jedis.del(lockKey);
//            flag = true;
//        }
//        return flag;
    }
}
